import logging
import traceback
from contextlib import asynccontextmanager
from typing import Optional

from fastapi import FastAPI, Request, HTTPException, Depends, Header
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles

from app.core.config import settings
from app.providers.how2solutions_provider import How2SolutionsProvider

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 应用启动时
    logger.info("应用启动中 (固定认证模式)...")
    # 在这里可以添加其他启动任务，如果需要的话
    yield
    # 应用关闭时
    logger.info("应用关闭中...")

app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description=settings.DESCRIPTION,
    lifespan=lifespan
)

# 挂载 static 目录
app.mount("/static", StaticFiles(directory="app/static"), name="static")

# 检查配置是否正确，如果配置不正确，FastAPI启动时会因这里的异常而失败
try:
    provider = How2SolutionsProvider()
except ValueError as e:
    logger.critical(f"无法启动服务: {e}")
    # 在实际生产中，你可能希望程序在这里退出
    import sys
    sys.exit(1)


async def verify_api_key(authorization: Optional[str] = Header(None)):
    """验证 API 密钥的依赖项。"""
    if settings.API_MASTER_KEY:
        if not authorization or "bearer" not in authorization.lower():
            raise HTTPException(status_code=401, detail="需要 Bearer Token 认证。")
        token = authorization.split(" ")[-1]
        if token != settings.API_MASTER_KEY:
            raise HTTPException(status_code=403, detail="无效的 API Key。")

@app.post("/v1/chat/completions", dependencies=[Depends(verify_api_key)])
async def chat_completions(request: Request):
    """
    处理聊天请求。
    注意：此端点为单次对话模型，不维护上下文。
    """
    try:
        request_data = await request.json()
        return await provider.chat_completion(request_data, request)
    except Exception as e:
        logger.error(f"处理聊天请求时发生顶层错误: {e}")
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=f"内部服务器错误: {e}")

@app.get("/v1/models", dependencies=[Depends(verify_api_key)])
async def list_models():
    """返回支持的模型列表。"""
    return await provider.get_models()

@app.get("/panel", response_class=HTMLResponse)
async def get_panel(request: Request):
    """提供可视化管理面板页面。"""
    with open("app/static/panel.html", "r", encoding="utf-8") as f:
        return HTMLResponse(content=f.read())

# 由于 worker_manager 已移除，状态面板不再可用，可以注释或移除此端点
# @app.get("/status", dependencies=[Depends(verify_api_key)])
# async def get_status():
#     """获取 Worker 管理器的状态，供面板调用。"""
#     return {"status": "ok", "mode": "fixed_authentication"}

@app.get("/")
def root():
    """根路由，提供服务基本信息。"""
    return {"message": f"欢迎来到 {settings.APP_NAME} v{settings.APP_VERSION}"}
